//
//  BaseWebController.swift
//  GreenLight
//
//  Created by ZWJY on 2022/8/19.
// 公共webView

import UIKit
import WebKit

class BaseWebController: BaseViewController {

    var urlString: String? {
        didSet{
            guard let urlString = urlString, !urlString.isEmpty else { return }
            var url = URL(string: urlString)
            if !urlString.contains("http") {
                url = URL(fileURLWithPath: urlString)
            }
            let request = URLRequest.init(url: url!)
            webView.load(request)
        }
    }

    private lazy var webView: WKWebView  = {
        let config = WKWebViewConfiguration.init()
        // 视频配置
        config.allowsInlineMediaPlayback = true
        config.allowsAirPlayForMediaPlayback = true
        config.allowsPictureInPictureMediaPlayback = true

        // 偏好设置
        let preferences = WKPreferences.init()
        preferences.javaScriptEnabled = true
        preferences.javaScriptCanOpenWindowsAutomatically = true

        config.preferences = preferences

        let view = WKWebView.init(frame: .zero, configuration: config)
        // 允许侧滑返回
        view.allowsBackForwardNavigationGestures = true
        view.navigationDelegate = self
        view.scrollView.contentInsetAdjustmentBehavior = .never
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }
}

extension BaseWebController {

    private func configUI() {
        setNav()
        addViews()
        addContraints()
    }
    
    private func setNav() {
        navigationBar.isHidden = true
    }

    private func addViews() {
        view.addSubview(webView)
    }

    private func addContraints() {
        webView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension BaseWebController: WKNavigationDelegate {

    // 开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    }

    // 开始返回内容
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    }

    // 页面加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    }

    // 加载时发生错误
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    }
}
